package com.project.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.project.core.util.ScoreContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author mengxj
 */
@Component
public class MetaDataHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Long currentUser = ScoreContext.currentUser().getId();
        LocalDateTime now = LocalDateTime.now();
        this.setProperties(metaObject, "createTime", now);
        this.setProperties(metaObject, "createBy", currentUser);
        this.setProperties(metaObject, "updateTime", now);
        this.setProperties(metaObject, "updateBy", currentUser);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long currentUser = ScoreContext.currentUser().getId();
        this.setProperties(metaObject, "updateTime", LocalDateTime.now());
        this.setProperties(metaObject, "updateBy", currentUser);
    }

    private void setProperties(MetaObject metaObject, String column, Object value){
        if(metaObject.hasSetter(column)){
            this.setFieldValByName(column, value, metaObject);
        }
    }
}
